package com.example.resource_station_backend.controller;


import com.example.resource_station_backend.common.BaseResponse;
import com.example.resource_station_backend.common.ResultUtils;
import com.example.resource_station_backend.dao.CategoryRepository;
import com.example.resource_station_backend.exception.ErrorCode;
import com.example.resource_station_backend.exception.ThrowUtils;
import com.example.resource_station_backend.model.dto.CategoryDTO;
import com.example.resource_station_backend.model.entity.Category;
import com.example.resource_station_backend.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @Author xinhao
 * @Description
 * @CreateTime 2025-02-25 21:47:37
 */
@RestController
@RequestMapping("/category")
public class CategoryController {

    @Autowired
    CategoryService categoryService;

    @Autowired
    CategoryRepository categoryRepository;

    /**
     * 需要返回分类信息，前端才能根据分类id找到分类名，对应url等
     */
    @GetMapping("/list")
    public BaseResponse<List<Category>> getCategoryList() {
        List<Category> categories = categoryRepository.findAll();
        ThrowUtils.throwIf(categories.isEmpty(), ErrorCode.NOT_FOUND_ERROR);
        return ResultUtils.success(categories);
    }

    /**
     * 通过分类的名称获取分类id
     */
    @GetMapping("/id")
    public BaseResponse<Long> getCategoryIdByName(String name) {
        ThrowUtils.throwIf(name == null, ErrorCode.PARAMS_ERROR);
        Long category_id = categoryRepository.findIdByName(name).get().getId();
        return ResultUtils.success(category_id);
    }

    /**
     * 通过分类的id获取分类的名称
     */
    @GetMapping("/name")
    public BaseResponse<String> getCategoryNameById(Long id) {
        ThrowUtils.throwIf(id == null || id <= 0, ErrorCode.PARAMS_ERROR);
        String name = categoryRepository.findById(id).get().getName();
        return ResultUtils.success(name);
    }

    // 比如管理员添加分类
    @PostMapping("/add")
    public BaseResponse<Long> addCategory(@RequestBody CategoryDTO categoryDTO) {
        ThrowUtils.throwIf(categoryDTO == null, ErrorCode.PARAMS_ERROR);
        return ResultUtils.success(categoryService.addCategory(categoryDTO));
    }

}
